<?php
require_once 'config21.php';
if (!isset($_SESSION['username'])) {
    header('Location: login21.php');
    exit();
}

if (isset($_GET['id'])) {
    $class_id = $_GET['id'];
    $sql = "SELECT * FROM classes WHERE class_id = $class_id";
    $result = $conn->query($sql);
    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
    } else {
        echo "未找到该班级信息";
        exit;
    }
} else {
    echo "缺少班级 ID";
    exit;
}

// 获取所有系部信息用于下拉选择
$dept_sql = "SELECT * FROM departments";
$dept_result = $conn->query($dept_sql);

// 修改班级
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['edit_class'])) {
    $class_name = $_POST['class_name'];
    $department_id = $_POST['department_id'];
    $sql = "UPDATE classes SET class_name = '$class_name', department_id = $department_id WHERE class_id = $class_id";
    if ($conn->query($sql)) {
        header('Location: class_management21.php');
        exit;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改班级</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h2>修改班级</h2>
    <form action="<?php echo $_SERVER['PHP_SELF'] . "?id=$class_id" ?>" method="post">
        <label for="class_name">班级名称:</label>
        <input type="text" name="class_name" value="<?php echo $row['class_name']; ?>" required><br>
        
        <label for="department_id">所属系部:</label>
        <select name="department_id" required>
            <?php
            while ($dept_row = $dept_result->fetch_assoc()) {
                $selected = ($dept_row['department_id'] == $row['department_id']) ? 'selected' : '';
                echo "<option value='" . $dept_row['department_id'] . "' $selected>" . $dept_row['department_name'] . "</option>";
            }
            ?>
        </select><br>
        
        <input type="submit" name="edit_class" value="修改">
    </form>
    <a href="class_management21.php">返回班级管理页面</a>
</body>
</html>